<?php
/**
 * @package base
 *
 */

/**
 * System related procedures.
 * Singleton
 *
 */
class System {
	/** limit of the execution counter */
	const MAX_EXECUTIONTIME = 30;
	/** beggining value of the counter */
	public static $scriptStartMicrotime = null;
	
	/** @see System */
	private static $system;
	
	/**
	 * Last value of the left time when counter is paused
	 */
	private static $timeLeftStopped;
	
	/**
	 * This class is a singleton
	 */
	private function __construct() {
		if (is_null(self::$scriptStartMicrotime))
			self::$scriptStartMicrotime = microtime(true);
	}
	
	/**
	 * Pause execution time counting.
	 */
	public static function stopMaxExecutionTimeCounting() {
		// TODO deal with debugging thus this won't work.
		set_time_limit(0);
		self::$timeLeftStopped = self::currentScriptExecutionTime();
	}
	
	/**
	 * Continue execution time counting.
	 */
	public static function continueMaxExecutionTimeCounting() {
		$newLimit = self::MAX_EXECUTIONTIME - (int)self::$timeLeftStopped;
		if ($newLimit > 0)
			set_time_limit($newLimit);
	}
	
	/**
	 * Current execution time in a counter.
	 */
	public static function currentScriptExecutionTime() {
		return microtime(true) - self::$scriptStartMicrotime;
	}
	
	/**
	 * Init function
	 * @see index.php
	 */
	public static function init() {
		self::$system = new System();
	}
	
	/**
	 * This method should be called whenever this application manages php
	 * script execution.
	 * It does save session.
	 * This method is not related to counter's method
	 */
	public static function finalScriptExecute() {
		$info = SiteContext::getSiteContext();
		
		$info->setPreviousPage();
		$_SESSION[Constants::PHP_SESSIONVAR] = serialize($info);
	}
}
?>